﻿using iTool.Common.Options;
using iTool.Utils;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace iTool.Utils
{
    public static class iAppSetting
    {
        static IConfiguration configuration;

        public static iToolConfigure iToolConfigure { get; private set; }
        public static bool IsDebug { get; set; }
        public static iToolConfigure OldiToolConfigure { get; private set; }

        public const string QueueServiceStreamNamespace = "iToolQueueServiceStream";

        public const string QueueConnectorStreamNamespace = "iToolQueueConnectorStream";

        public const string ScriptEditTopic = "EDIT_FUNCTIONS";
        public const string ScriptDeleteTopic = "SCRIPT_DELETE";
        public const string ScriptBudilerTopic = "SCRIPT_BUDILER";
        public const string INSTALLPACKAGETOPIC = "INSTALL_PACKAGE";

        static iAppSetting()
        {
            var framework = "framework.json";
#if DEBUG
            framework = "framework.debug.json";
            IsDebug = true;
#endif

            // 环境变量
            var builder = new ConfigurationBuilder().AddJsonFile(framework, true, true);
            configuration = builder.Build();
        }

        public static bool ReSetiToolConfigure(iToolType iToolType = iToolType.None)
        {
            try
            {
                string currentDirectory = string.Empty;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    currentDirectory = $"D:/iTool-Cloud-Framework";
                    //currentDirectory = Directory.GetCurrentDirectory();
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    currentDirectory = "/var/iTool";
                }


                string _iToolConfigurePath = $"{currentDirectory}/{(IsDebug ? "Debug.iToolConfig" : "Release.iToolConfig")}";
                System.Console.WriteLine("_iToolConfigurePath:{0}", _iToolConfigurePath);

                OldiToolConfigure = iToolConfigure;
                if (File.Exists(_iToolConfigurePath))
                {
                    var content = File.ReadAllText(_iToolConfigurePath);
                    iToolConfigure = JsonConvert.DeserializeObject<iToolConfigure>(content);

                    switch (iToolType)
                    {
                        case iToolType.Connector:
                            return IsConnectorNeedRestart();
                        case iToolType.Service:
                            return IsServerNeedRestart();
                        default:
                            return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (System.Exception)
            {
                return false;
            }
        }

        public static bool IsExist(string key)
        {
            return
                !string.IsNullOrWhiteSpace(configuration.GetSection(key)?.Value);
        }

        public static string GetValue(string key)
        {
            return configuration.GetSection(key).Value;
        }

        public static void SetValue(string key, string value)
        {
            configuration.GetSection(key).Value = value;
        }

        public static string[] GetArray(string key)
        {
            return GetValue(key).TryToEntity<string[]>();
        }
        public static IEnumerable<T> GetArray<T>(string key)
        {
            return GetValue(key).TryToEntity<IEnumerable<T>>();
        }
        public static void Bind<T>(T mySettings)
        {
            mySettings = configuration.ToString().TryToEntity<T>();
        }
        public static void Bind<T>(string key, T mySettings)
        {
            mySettings = GetValue(key).TryToEntity<T>();
        }

        public static bool GetValueOfBool(string key)
        {
            return GetValue(key) == "True";
        }

        public static T GetValue<T>(string key)
        {
            var value = JsonConvert.DeserializeObject<T>(GetValue(key));
            return value;
        }

        public static string GetConnectionString(string key)
        {
            return configuration.GetConnectionString(key);
        }


        private static bool IsServerNeedRestart()
        {
            if (OldiToolConfigure.ServerPort != iToolConfigure.ServerPort)
            {
                return true;
            }
            if (OldiToolConfigure.ServerGatewayPort != iToolConfigure.ServerGatewayPort)
            {
                return true;
            }
            if (OldiToolConfigure.iToolBaseDatabases.First() != iToolConfigure.iToolBaseDatabases.First())
            {
                return true;
            }

            return false;
        }

        private static bool IsConnectorNeedRestart()
        {
            if (OldiToolConfigure.Port != iToolConfigure.Port)
            {
                return true;
            }
            if (OldiToolConfigure.ServerPort != iToolConfigure.ServerPort)
            {
                return true;
            }
            if (OldiToolConfigure.ServerGatewayPort != iToolConfigure.ServerGatewayPort)
            {
                return true;
            }
            if (OldiToolConfigure.iToolBaseDatabases.First() != iToolConfigure.iToolBaseDatabases.First())
            {
                return true;
            }
            if (OldiToolConfigure.ElasticSearchProviders.First().TryToJson() != iToolConfigure.ElasticSearchProviders.First().TryToJson())
            {
                return true;
            }

            return false;
        }


    }
}
